import 'package:dify_api/entities/conversation.dart';
import 'package:flutter/material.dart';
import 'package:fstudy/src/common/helper.dart';

// 会话列表
class ConversationItemsProvider with ChangeNotifier {
  List<Conversation>? _items;

  List<Conversation> get items {
    return _items ?? [];
  }

  // 重置会话数据
  Future<void> reset(List<Conversation>? items) async {
    if (null == items) {
      await loadData();
    } else {
      _items = items;
      notifyListeners();
    }
  }

  Future<void> loadData() async {
    bool hasMore = true;
    String? lastId;

    List<Conversation> lst = [
      // 默认包含创建新会话功能
      Conversation(
        id: "",
        name: "新会话",
        inputs: {},
        status: "",
        introduction: "",
        createdAt: 0,
        updatedAt: 0,
      ),
    ]; // 清空数据

    do {
      var query = {
        'user': config().deviceId,
        'last_id': lastId,
        'sort_by': '-created_at',
      };

      final response = await api().get(
        '/conversations',
        queryParameters: query,
      );

      final List<dynamic> data = response.data['data'];

      for (var item in data) {
        lst.add(Conversation.fromJson(item));
      }
      if (lst.isNotEmpty) {
        hasMore = response.data['has_more'];
        if (hasMore) {
          lastId = data.last['id'];
        }
      } else {
        hasMore = false;
      }
    } while (hasMore);

    _items = lst;

    notifyListeners();
  }
}

// 当前会话ID
class CurrentConversationProvider with ChangeNotifier {
  String id = "";

  void change(String newId) {
    id = newId;
    notifyListeners(); // 强制刷新
  }
}
